import Common from './common'
import { Data } from '../Data/data'
export default class CommonAction extends Laya.Script {
    public aff = 1
    public wx
    public systemInfo: any;

    public static hadRewardVideo = false;
    public rewardedShortVideoAd: any;//激励短视频
    // public rewardedShortVideoAdunitId = "adunit-b2fde6bff06175c4";//微信
    public rewardedShortVideoAdunitId = "13e7gb2k2m3164ha6e";//头条

    public rewardedVideoAd: any;
    // public rewardedVideoAdUnitId = "adunit-3ea5b766c48fb0d0";//微信
    public rewardedVideoAdUnitId = "ehh8m67bgr78loeejc"//头条
    public version = "";

    public gameRecorderManager;//头条录屏管理器

    public bannerAd: any;
    public bannerAdUnitIds = ["18lnk46kh3kb22ha7i"];//banner广告

    public interstitialAd: any;
    public interstitialAdUnitId = "24857k88k0212g2426";//插屏广告

    constructor() {
        super();
        if (Laya.Browser.onMiniGame) {
            //获取微信接口
            this.wx = Laya.Browser.window.wx;
        }
        this.commonBtnEvent()
    }

    public commonBtnEvent() {
        this.getToken()
        //授权
        if (Common.platform == "weixin") {
            console.log("hahahaha")
            Laya.stage.on("Authorize", this, this.wxAuthorize);
        } else {
            Laya.stage.on("Authorize", this, this.authorize);
        }

        this.systemInfo = this.wx.getSystemInfoSync();
        this.version = this.wx.env.VERSION;
        Common.toutiaoAppName = this.systemInfo.appName;
        Laya.stage.on("ShowMsg", this, this.showMsg);
        Laya.stage.on("wxShare", this, this.wxShare)
        if (this.version != "development" || Common.platform == "weixin") {
            this.createRewardedVideoAd();
            this.createRewardedShortVideoAd();

            Laya.stage.on("showRewardedVideoAd", this, this.showRewardedVideoAd);
            Laya.stage.on("showRewardedShortVideoAd", this, this.showRewardedShortVideoAd);
            if (!CommonAction.hadRewardVideo) {
                CommonAction.hadRewardVideo = true;
                this.listenRewardedVideoAd();
            }
        }

        if (Common.platform == "toutiao") {
            this.getRecorderManager()
            this.recordOnStop();
            Laya.stage.on("TtShare", this, this.ttShare);
            //开始录屏
            Laya.stage.on("RecordStart", this, this.recordStart);
            //结束录屏
            Laya.stage.on("RecordStop", this, this.recordStop);
        }

        if (Common.toutiaoAppName === "Toutiao") {
            //插屏广告
            this.createInterstitialAd();
            Laya.stage.on("ShowInterstitialAd", this, this.showInterstitialAd);
        }

        this.createAndShowBannerAd();
        Laya.stage.on("showBannerAd", this, this.showBannerAd);
        Laya.stage.on("hideBannerAd", this, this.hideBannerAd);
    }

    getToken() {
        let _self = this;
        if (Common.getCacheItem("loginToken") == null) {
            _self.wx.login({
                "force": false,
                //执行登录操作，如果没登录则会调起登录操作
                success(res) {
                    console.log("已登录成功");
                    console.log(res);
                    let anonymousCode = null;
                    if (Common.platform == "toutiao") {
                        anonymousCode = res.anonymousCode
                    }
                    if (res.code == null) {//未登录则直接进行匿名登录
                        _self.defaultAction()
                    }
                    _self.loginServer(res.code, anonymousCode);
                    // //登录成功后开始授权
                }, fail(res) {
                    console.log(`login调用失败`);
                    console.log(res)

                }
            });
        }
    }

    loginServer(code: string, anonymousCode: string) {
        var yhr = new Laya.HttpRequest();
        yhr.http.timeout = 10000;
        yhr.once(Laya.Event.ERROR, this, this.yErrorHandler);
        yhr.once(Laya.Event.COMPLETE, this, this.yCompleteHandler);
        let uri = "/app/login?appId=" + Common.appId + "&aff=" + this.aff + "&platform=" + Common.platform + "&code=" + code + "&anonymousCode=" + anonymousCode;
        // if(this.parentId != null){
        //     uri += "&parentId="+this.parentId
        // }
        yhr.send(Common.requestBaseUrl + uri, "", "get", "json");

    }
    /**请求错误时调用 */
    yErrorHandler(data) {
        Laya.stage.event("ShowMsg", "登录加载有问题，请重新打开小游戏");
        console.log("请求错误:" + data);
    }

    /**请求结束时调用，获取服务器数据 */
    yCompleteHandler(data) {
        console.log("登录加载数据成功")
        console.log(data);
        if (data != null && data.code == 0) {
            Data.UserData.loginToken = data.data.token;
            Common.setCacheItem("loginToken", data.data.token);
            Common.setCacheItem("openid", data.data.baseData.openid);
            Common.setCacheItem("userId", data.data.baseData.id);
            Data.UserData.openid = data.data.baseData.openid;
            Data.UserData.userId = data.data.baseData.id;
        } else {
            // Laya.stage.event("ShowMsg","登录加载有问题，请重新打开小游戏");
        }
    }

    /**
     * 微信授权
     */
    wxAuthorize(btn: any, eventName: string) {
        console.log("wx")
        if (Common.getCacheItem("nick") == null) {
            console.log(btn)
            let _self = this;
            let sysInfo = _self.wx.getSystemInfoSync();
            let screenW = sysInfo.screenWidth;
            let screenH = sysInfo.screenHeight;
            let rateW = screenW / 1080;//设计分辨率为750*1334
            let lasth = 1080 * sysInfo.windowHeight / sysInfo.windowWidth; //根据宽高比先求出实际高度
            let rateH = sysInfo.windowHeight / lasth;
            const button = _self.wx.createUserInfoButton({
                type: 'text',
                text: '',
                style: {
                    left: eventName == "startGame" ? (btn.x - btn.width / 2) * rateW : btn.x * rateW,
                    top: eventName == "startGame" ? (btn.y - btn.height / 2) * rateW : btn.y * rateH,
                    width: btn.width * rateW,
                    height: btn.height * rateH,
                    lineHeight: 40,
                    backgroundColor: '',
                    color: '#ffffff',
                    plain: true,
                    textAlign: 'center',
                    fontSize: 16,
                    borderRadius: 10
                }
            })
            Common.wxAuthButtonArr.push(button);
            console.log(button)
            button.onTap((res) => {
                Laya.stage.event("playSound", ["sound/tap.mp3"])
                console.log(res)
                console.log(Common.lastAuthCallbackEventName)
                Common.lastAuthCallbackEventName = eventName;
                if (res.errMsg == "getUserInfo:ok") {
                    let userInfo = res.userInfo;
                    console.log("授权用户信息")
                    console.log(userInfo);
                    userInfo['sex'] = userInfo["gender"];
                    _self.userInfoAtion(userInfo);
                    if (Common.wxAuthButtonArr.length > 0) {
                        Common.wxAuthButtonArr.forEach(button => {
                            //清除微信授权按钮
                            button.destroy()
                        });
                    }
                } else {

                    _self.showMsg("为了更好的游戏体验，请同意授权用户信息哦");
                    //_self.defaultAction();
                }




            })
        }
    }

    /**
    * 头条授权
    */
    public authorize() {
        let _self = this;
        _self.wx.authorize({
            scope: 'scope.userInfo',
            success(aus) {
                console.log("授权成功");
                console.log(aus);
                //授权成功的开始获取用户信息
                _self.wx.getUserInfo({
                    success(gs) {
                        console.log("获取用户信息");
                        console.log(gs);
                        _self.userInfoAtion(gs.userInfo);
                        _self.showMsg("授权成功");

                    },
                    fail(gf) {
                        console.log("获取不到用户信息");
                        console.log(gf);
                        //self.loginGame(res.code);

                    }, complete() {
                        //无论成功还是失败都执行一次登录操作

                    }
                })
            }, fail(auf) {
                _self.wx.showModal({

                    title: "温馨提示",

                    content: "同意授权能更好体验游戏哦，可前往设置开启授权",

                    showCancel: true,

                    cancelText: "取消",

                    confirmText: "确认",

                    success: function (e) {
                        if (e.confirm) {
                            _self.wx.openSetting({
                                success: (res) => { }
                            })
                        } else {
                            _self.defaultAction();
                        }
                    }

                });
                //_self.showMsg("同意授权能更好体验游戏哦，我们会保护您的隐私。");
                console.log("拒绝授权，授权失败");
                console.log(auf);

            }
        });
    }


    /**
     * 未授权默认的动作
     */
    private defaultAction() {
        let _self = this;
        Common.setCacheItem("avatarUrl", "");
        Common.setCacheItem("province", "unkown");
        Common.setCacheItem("city", "unkown");
        Common.setCacheItem("nick", "游客");
        let userInfo = {};
        userInfo['avatarUrl'] = "";
        userInfo['nickName'] = "游客";
        userInfo['sex'] = 0;
        _self.showMsg("当前已使用匿名的身份进行游戏");
        _self.userInfoAtion(userInfo);
    }

    /**
     * 
     * @param _self 已授权的动作
     * @param userInfo 
     */
    private userInfoAtion(userInfo) {
        let _self = this;
        // let userInfo=gs.userInfo;
        // 获取到用户信息
        // _self.showMsg("授权成功");
        let sex = 2;
        if (userInfo['sex'] == 1) {
            sex = 0;
        } else if (userInfo['sex'] == 2) {
            sex = 1;
        }
        //授权成功后执行回调
        // if(callback == "wxShare"){
        //     _self.wxShare(args1,args2);
        // }

        Common.setCacheItem("province", userInfo['province']);
        Common.setCacheItem("city", userInfo['city']);
        Common.setCacheItem("nick", userInfo['nickName']);
        Common.setCacheItem("avatarUrl", userInfo['avatarUrl'].replace("http://","https://"));

        _self.updateInfo(userInfo['nickName'], userInfo['avatarUrl'], sex, userInfo['province'], userInfo['city'], "");

        //授权成功后执行回调
        console.log(Common.lastAuthCallbackEventName);
        Laya.stage.event(Common.lastAuthCallbackEventName, Common.lastAuthCallbackEventArgs);
    }

    updateInfo(nick: string, portrait: string, sex: number, province: string, city: string, age: string) {
        var yhr = new Laya.HttpRequest();
        yhr.http.timeout = 10000;
        yhr.once(Laya.Event.ERROR, this, this.updateInfoErrorHandler);
        yhr.once(Laya.Event.COMPLETE, this, this.updateInfoCompleteHandler);
        let uri = "/app/updateInfo?token=" + Common.getCacheItem('loginToken');
        uri += "&nick=" + nick;
        uri += "&portrait=" + portrait;
        uri += "&sex=" + sex;
        uri += "&province=" + province;
        uri += "&city=" + city;
        uri += "&age=" + age;
        yhr.send(Common.requestBaseUrl + uri, "", "get", "json");

    }
    /**请求错误时调用 */
    updateInfoErrorHandler(data) {
        // Laya.stage.event("ShowMsg","授权信息有误，请重新授权");
    }

    /**请求结束时调用，获取服务器数据 */
    updateInfoCompleteHandler(data) {
        console.log(data);
        if (data == null || data.code != 0) {
            // Laya.stage.event("ShowMsg","授权信息有误，请重新授权");
        }
    }

    //创建激励广告
    createRewardedVideoAd() {
        this.rewardedVideoAd = this.wx.createRewardedVideoAd({
            adUnitId: this.rewardedVideoAdUnitId,
            multiton: false
        })
    }

    // 用户触发广告后，显示激励视频广告 
    showRewardedVideoAd() {
        console.log("show read ")
        this.rewardedVideoAd.show().catch(() => {
            // 失败重试
            this.rewardedVideoAd.load()
                .then(() => this.rewardedVideoAd.show())
                .catch(err => {
                    console.log('激励视频 广告显示失败')
                })
        })
    }

    listenRewardedVideoAd() {
        let _self = this;
        //监听道具视频广告结束
        this.rewardedVideoAd.onClose((res: any) => {
            console.log("为什么会执行这个");
             //res.isEnded = true;
            if (res.isEnded) {
                console.log("视频看完");
                console.log(Common.lastRewardedVideoEventName)
                Laya.stage.event(Common.lastRewardedVideoEventName)
            } else {
                _self.showMsg('需要完整看完视频才可获得');
            }
            if (Common.getCacheItem("musicSetting") == "1" || Common.getCacheItem("musicSetting") == null) {
                Laya.stage.event("playMusic");//微信分享会停止音乐，检测如果音乐设置是开启就启动
            }

        })
    }


    //创建激励广告
    createRewardedShortVideoAd() {
        this.rewardedShortVideoAd = this.wx.createRewardedVideoAd({
            adUnitId: this.rewardedShortVideoAdunitId,
            multiton: false
        })
        this.rewardedShortVideoAd.onError((res) => {
            console.log(res)
            let errCode = res.errCode;
            switch (errCode) {
                case 1000:
                    console.log("后端接口调用失败")
                    break;
                case 1004:
                    this.showMsg("暂无可看的视频!");
                    console.log("暂无可用的广告")
                    break;
                case 1007:
                    console.log("广告组件被封禁")
                    break;
                case 1008:
                    console.log("广告单元被关闭")
                    break;
            }
        })
    }

    // 用户触发广告后，显示激励视频广告 
    showRewardedShortVideoAd() {
        console.log("show read ")
        this.rewardedShortVideoAd.show().catch(() => {
            // 失败重试
            this.rewardedShortVideoAd.load()
                .then(() => this.rewardedShortVideoAd.show())
                .catch(err => {
                    console.log('激励视频 广告显示失败')
                })
        })
    }

    /**
     * 展示信息
     * @param msg 
     */
    showMsg(msg: string, duration: number = 2000) {
        let obj = this;
        obj.wx.showToast({ icon: 'none', title: msg, duration: duration });
    }

    /**分享好友模块 */
    wxShare(source: number, imgUrl: string) {
        // if(Common.getCacheItem("nick") == null){
        //     Laya.stage.event("Authorize",["wxShare",source,imgUrl]);
        //     return false;
        // }

        let query = "";
        let title
        if (source == 1) {
            title = "我在我要穿越中获得了小飞机，等你来战！"
        } else if (source == 2) {
            title = "我在我要穿越中获得了小飞船，等你来战！"
        } else if (source == 3) {
            title = "我在我要穿越中获得了火箭，等你来战！"
        } else if (source == 4) {
            title = "我在我要穿越中获得了冲天艇，等你来战！"
        } else if (source == 5) {
            title = "我在我要穿越中获得了宇航员，等你来战！"
        } else if (source == 6) {
            title = "我在我要穿越中获得了外星人，等你来战！"
        } else if (source == 7) {
            title = Common.shareTitle
        }//source = 7时为自定义

        let templateId = null;
        if (Common.platform == "toutiao" && imgUrl == null) {
            templateId = "4j8k09af1a1l26imch";
        } else if (Common.platform == "weixin" && imgUrl == null) {
            imgUrl = "https://mmocgame.qpic.cn/wechatgame/IaibtBUbbfY0mqS0QYtteTmTfXg8OlQcdHuzy6ZVLWBKCT7KBziaFbiaVibiaOa6iagNOG/0";
            templateId = "qGDvxbn1SnK1LntSTjOgXQ==";//微信
        }


        this.wx.shareAppMessage({
            title: title,
            imageUrl: imgUrl,
            templateId: templateId,
            imageUrlId: templateId,
            query: query, //JSON.stringify(WebSocketCtrl.roomId)
            success() {
                this.showMsg("分享成功")
                console.log("分享成功");

            },
            fail(e) {
                console.log("分享失败");
            }
        })
    }

    getRecorderManager() {
        this.gameRecorderManager = this.wx.getGameRecorderManager();
    }
    //开始录屏
    recordStart() {
        console.log("开始录屏")
        Common.lastVideoStartTime = Common.getCurrentTime();
        this.gameRecorderManager.start({
            duration: 180,
        });
    }
    //结束录屏
    recordStop() {
        let nDate = new Date();
        let pT = Date.parse(nDate.toUTCString());
        Common.lastVideoSecond = (pT - Common.lastVideoStartTime) / 1000;//录屏时长
        console.log("结束录屏")
        this.gameRecorderManager.stop();
    }
    //录屏结束事件
    recordOnStop() {
        this.gameRecorderManager.onStop((res) => {
            console.log("录屏结束")
            console.log(res);
            Common.lastVideoPath = res.videoPath;
        })
    }
    //分享录屏
    ttShare(title: string) {
        let _self = this;
        if (Common.lastVideoSecond < 5) {
            _self.showMsg("您录制的视频过短，需重新录制后分享");
            return;
        } else if (Common.lastVideoSecond > 60) {
            _self.showMsg("您录制的视频较长，若有奖励将会在视频发布成功后发放，请勿离开当前小游戏。");
        }
        console.log(_self);
        console.log(Common.lastVideoPath);
        _self.wx.shareAppMessage({
            channel: "video",
            title: title,//转发标题
            desc: "我就不信你能穿越2个星球！",//分享文案
            imageUrl: "https://c.leaf-tech.net/upload/share1.png",
            templateId: "", // 替换成通过审核的分享ID
            query: "",
            extra: {
                videoPath: Common.lastVideoPath, // 可替换成录屏得到的视频地址
                videoTopics: ["宇宙", "穿越", "小游戏","星球","星际穿越"],//视频话题
                withVideoId: true   //是否支持跳转到播放页
            },
            success(res) {
                console.log(res.videoId);
                console.log("分享视频成功");
                _self.showMsg("分享视频成功");
            },
            fail(e) {
                console.log(e);
                _self.showMsg("分享视频失败，请重试");
                console.log("分享视频失败");
            }
        });
    }

    //创建并显示Banner广告
    createAndShowBannerAd() {
        console.log("创建BannerAD")
        var phone = this.wx.getSystemInfoSync();
        var windowWidth = phone.windowWidth;
        var windowHeight = phone.windowHeight;
        console.log(windowHeight);
        var targetBannerAdWidth = 200;
        // this.bannerAd = this.wx.createBannerAd({
        //     adUnitId: this.bannerAdUnitId,
        //     adIntervals:30,
        //     style: {
        //       width: 200,
        //     }
        // });
        //   //底部居中
        // this.bannerAd.onResize(res => {
        //    // console.log(res)
        //     this.bannerAd.style.top = windowHeight - res.height;
        //     this.bannerAd.style.left = (windowWidth - res.width) / 2; // 水平居中
        // });
        console.log(this.bannerAdUnitIds);
        this.bannerAd = this.wx.createBannerAd({
            adUnitId: this.bannerAdUnitIds[0],
            adIntervals: 30,
            style: {
                width: 300,
            }
        });
        //底部居中
        this.bannerAd.onResize(res => {
            // console.log(res)
            this.bannerAd.style.top = windowHeight - res.height;
            this.bannerAd.style.left = (windowWidth - res.width) / 2; // 水平居中
        });
        this.bannerAd.onError((res) => {
            console.log(res)
            let errCode = res.errCode;
            switch (errCode) {
                case 1000:
                    console.log("后端接口调用失败")
                case 1003:
                    console.log("后端接口调用失败")
                    break;
                case 1007:
                    this.showMsg("暂无可看的视频!");
                    console.log("暂无可用的广告")
                    break;
                case 1007:
                    console.log("广告组件被封禁")
                    break;
                case 1008:
                    console.log("广告单元被关闭")
                    break;
            }
        })

        console.log("显示BannerAD")



    }

    showBannerAd() {
        let _self = this;
        this.bannerAd.onLoad(function () {
            _self.bannerAd
                .show()
                .then(() => {
                    console.log("广告显示成功");
                })
                .catch(err => {
                    console.log("广告组件出现问题", err);
                });
        });
    }

    // //隐藏Banner广告
    hideBannerAd() {
        this.bannerAd.hide();
    }

    //创建插屏广告
    createInterstitialAd() {
        try {
            this.interstitialAd = this.wx.createInterstitialAd({
                adUnitId: this.interstitialAdUnitId,
            })
            this.interstitialAd.onError((res) => {
                console.log(res)
                let errCode = res.errCode;
                switch (errCode) {
                    case 1000:
                        console.log("后端接口调用失败")
                        break;
                    case 1004:
                        console.log("暂无可用的广告")
                        break;
                    case 1007:
                        console.log("广告组件被封禁")
                        break;
                    case 1008:
                        console.log("广告单元被关闭")
                        break;
                }
            })
        } catch (err) {
        }


    }

    //\显示插屏广告
    showInterstitialAd() {
        console.log("show read ")
        if (this.interstitialAd != null) {
            this.interstitialAd.show().catch(() => {
                // 失败重试
                this.interstitialAd.load()
                    .then(() => this.interstitialAd.show())
                    .catch(err => {
                        console.log('插屏 广告显示失败')
                    })
            })
        }

    }


    //\显示插屏广告
    closeInterstitialAd() {
        console.log("show read ")
        if (this.interstitialAd != null) {
            this.interstitialAd.close().catch(() => {
                console.log('插屏 广告关闭失败')
            })
        }

    }

}

